package com.wxzhou.wangzhuan.security;

import com.wxzhou.wangzhuan.util.RedisKeyUtil;
import io.quarkus.redis.datasource.ReactiveRedisDataSource;
import io.quarkus.redis.datasource.hash.ReactiveHashCommands;
import io.quarkus.redis.datasource.keys.ReactiveKeyCommands;
import io.quarkus.redis.datasource.value.ReactiveValueCommands;
import io.smallrye.mutiny.Uni;
import jakarta.inject.Inject;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.container.ContainerRequestFilter;
import jakarta.ws.rs.container.PreMatching;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.SecurityContext;
import jakarta.ws.rs.ext.Provider;
import org.jboss.logging.Logger;

import java.time.Duration;
import java.util.Optional;

/**
 * 认证过滤器 - 用于调试认证流程（可选认证）
 */
@Provider
@PreMatching
public class AuthenticationFilter implements ContainerRequestFilter {

    private static final Logger LOG = Logger.getLogger(AuthenticationFilter.class);

    @Inject
    ReactiveRedisDataSource redisDataSource;

    @Inject
    RedisKeyUtil redisKeyUtil;

    @Override
    public void filter(ContainerRequestContext requestContext) {
        String path = requestContext.getUriInfo().getPath();
        String method = requestContext.getMethod();

        checkAndCacheParams(requestContext);
        // 检查是否有认证信息
        SecurityContext securityContext = requestContext.getSecurityContext();
        if (securityContext != null && securityContext.getUserPrincipal() != null&& securityContext.getUserPrincipal().getName() != null) {
            LOG.debug("用户已认证 path=" + path + ", method=" + method + ", user=" + securityContext.getUserPrincipal().getName());
        } else {
            LOG.debug("用户未认证 path=" + path + ", method=" + method);
        }
    }

    /**
     * 校验请求参数是否包含device-id（headers）和pid以及channel，如果是，则表示用户有邀请来源，并且请求书content-type=application/json
     * 将内容缓存到redis中
     *
     * @param requestContext
     * @return
     */
    private boolean checkAndCacheParams(ContainerRequestContext requestContext) {
        String deviceId = requestContext.getHeaders().getFirst("device-id");
        String pid = requestContext.getHeaders().getFirst("pid");
        String channel = requestContext.getHeaders().getFirst("channel");
//        String inCode = requestContext.getUriInfo().getQueryParameters().getFirst("inCode");

//        if (isNotBlank(deviceId) && isNotBlank(pid)) {
//
//            ReactiveValueCommands<String, String> values = redisDataSource.value(String.class);
//            String cacheKey = redisKeyUtil.buildShareKey();
//            values.get(cacheKey)
//                    .onItem().transformToUni(x -> values.setex(cacheKey, 300L, "1"))
//                    .subscribe().with(
//                            ok -> LOG.debug("Replay protection cached sign="),
//                            err -> LOG.error("Replay protection cache failed error=" + err.getMessage())
//                    );
//
//
//        }
        return isNotBlank(deviceId) && isNotBlank(pid) && MediaType.APPLICATION_JSON_TYPE.equals(requestContext.getMediaType());
    }

    private boolean isNotBlank(String str) {
        return str != null && !str.isEmpty() && !str.isBlank();
    }
} 